#!/bin/sh
. /etc/utils.sh

register_experiment CacheWarming
register_experiment DNSTimingLog

case "$1" in
  start)
    mkdir -p /config/dnsmasq
    mkdir -p /tmp/dnsmasq
    for d in /config/dnsmasq/* /tmp/dnsmasq/*; do
      # Remove symlinks in /config/dnsmasq.  Some existed in an earlier build
      # and interfere.
      if [ -h "$d" ]; then
        echo " -- Removing $d --"
        rm -f "$d"
      fi
      [ -e "$d" ] || continue
      echo "--- $d: ---"
      cat "$d"
      echo "---"
    done | logos dnsmasq
    if [ ! -r /tmp/resolv.conf.external ]; then
      # mainly happens with nfsroot
      cp /etc/resolv.conf /tmp/resolv.conf.external ||
      touch /tmp/resolv.conf.external
    fi

    if [ -x /bin/cache_warming/cache_warming.py ] && experiment CacheWarming; then
      babysit 60 /bin/cache_warming/cache_warming.py 2>&1 | logos cachewarming &
    fi

    # Stand-alone bridge mode for network type boxes.
    # When there is no wan0 link, don't run dnsmasq dhcp server on br0.
    basic_bridge_dhcp_disable=""
    if [ -e "/sys/class/net/wan0" -a -e "/sys/class/net/br0" ]; then
      if ! is-interface-up wan0; then
        basic_bridge_dhcp_disable="--except-interface br0"
      fi
    fi

    babysit 60 dnsmasq \
        $basic_bridge_dhcp_disable \
        --pid-file=/var/run/dnsmasq.pid \
        --conf-file=/etc/dnsmasq.conf \
        --resolv-file=/tmp/resolv.conf.external \
        --keep-in-foreground \
        --log-facility=- 2>&1 | logos dnsmasq &
    babysit 60 dnsmasqstats 2>&1 | logos dnsmasqstats &
    ;;
  stop)
    pkillwait cache_warming
    pkillwait -x dnsmasq
    pkillwait -x dnsmasqstats
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac

exit 0
